package rpc_netty.Serializer;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_1.Service.RpcException;
import rpc_netty.interfaces.CommonSerializer;

import javax.sql.rowset.serial.SerialException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HessianSerializer implements CommonSerializer {
    public static final Logger logger= LoggerFactory.getLogger(HessianSerializer.class);

    @Override
    public byte[] serialize(Object object) {
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        Hessian2Output out=new Hessian2Output(bos);
        try {
            out.startMessage();
            out.writeObject(object);
            out.completeMessage();
            out.close();
        }catch (Exception e){
            logger.error("error when serializing");
        }
        byte[] bytes = bos.toByteArray();
        return bytes;
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            Hessian2Input input = new Hessian2Input(bis);
            input.startMessage();
            Object o = input.readObject(clazz);
            input.completeMessage();
            input.close();
            return o;
        }catch (Exception e){
            logger.error("error when deserializing");
        }
        return null;
    }

    @Override
    public int getCode() {
        return SerializerCode.valueOf("Hessian").getCode();
    }
}
